<template lang="pug">
  .CustomerSalaryImportModal
    Modal(
      v-model="isShowCustomerSalaryImportModal"
      title="薪资导入"
      class-name="vertical-center-modal"
      width="700"
    )
      Form.has-rules-item2(ref="formImport" :model="formImport" :rules="rules" :label-width="180")
        FormItem.form-item(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop" v-show="item.isShow")
          template(v-if="item.type === 'text'")
            .line-h-30 {{formImport[item.model]}}
          template(v-if="item.type === 'input'")
            Input(v-model="formImport[item.model]" :placeholder="item.placeholder")
          template(v-if="item.type === 'radio'")
            RadioGroup.pt-0(v-model="formImport[item.model]" @on-change="listenCall(item.fn, formImport[item.model])")
              Radio.display-inline-block(v-for="c_item of item.radioArr" :label="c_item.value") {{c_item.label}}
          template(v-if="item.type === 'select'")
            Select(v-if="item.model === 'customerName'" v-model="formImport[item.model]" filterable :placeholder="item.placeholder" @on-change="listenCall(item.fn, formImport[item.model])")
              Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.id") {{c_item.name}}
            Select(v-else v-model="formImport[item.model]" :placeholder="item.placeholder")
              Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.text}}
          template(v-if="item.type === 'datePicker'")
            DatePicker.w-100(:value="formImport[item.model]" :placeholder="item.placeholder" type="month" @on-change="taxMonth(item.model, $event)")
          template(v-if="item.type === 'interval'")
            DatePicker.pull-left(:value="salaryStartTimeDefault" :placeholder="item.placeholder1" type="date" :options="dateOptionsStart" @on-change="handleChangeDatePicker(item.model1, $event)")
            span.pl-10.pr-10.line-h-32.pull-left --
            DatePicker.pull-left(:value="salaryEndTimeDefault" :placeholder="item.placeholder2" type="date" :options="dateOptionsEnd" @on-change="handleChangeDatePicker(item.model2, $event)")
          template(v-if="item.model === 'fileName'")
            Row
              Col.pl-10(span="24")
                Button.pull-left.mr-10(v-show="isCustomerTemplate" :to="customerTemplateDownLoadUrl" target="_blank") 自定义模板下载
                Button.pull-left.mr-10(v-show="!isCustomerTemplate" :to="templateDownLoadUrl" target="_blank") 模板下载
                Upload(
                  ref="upload"
                  :max-size="10 * 1024"
                  :on-exceeded-size="handleMaxSizeTen"
                  :action="baseUrl + 'api/CustomerSalary/Upload'"
                  :before-upload="handleBeforeUpload"
                  :on-success="handleUploadSuccess"
                  :on-remove="handleUploadRemove"
                  accept=".xls, .xlsx"
                  :headers="headers"
                )
                  Button(type="info" :loading="importExcel.uploadLoading" @click="handleUploadFile" :disabled="!isCanUpload") 导入
              Col.pl-10(span="24")
                .text-gray-9.pb-10 仅支持上传10M以内的xlsx文件
            Row(v-if="errorData.isError && !isCanUpload")
              Col.pl-10(span="24")
                //- Button(type="info") 导出错误数据附件
                //- a(type="primary" :href="errorData.downLoadUrl") 导出错误数据附件
                Button(type="warning" :to="errorData.downLoadUrl" target="_blank") 错误数据下载
              //- Col.pl-10(span="24")
              //-   input.pull-left.mr-10(type="file" @change="fileChange")
              //-   a(type="primary" :href="downLoadUrl") 模板
      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(v-if="isNowMonth" type="primary" @click="handleShowFurtherModal") 确定
        Button(v-if="!isNowMonth" type="primary" @click="handleImport" :loading="!isCanSubmit") 确定

      //- Table(:columns="importExcel.tableTitle" :data="importExcel.tableData" :loading="importExcel.tableLoading")
    Modal(
      v-model="isShowFurtherModal"
      class-name="vertical-center-modal"
      width="480"
      @on-ok="handleImport"
    )
      p.font-16.text-center.pt-20.pb-20 当前月份账单未核对，请认真检查后再导入薪资！
</template>

<script>
import moment from 'moment'
import { Common } from '@/utils/common.js'
import { CustomerSalaryApi } from '@/api/CustomerSalary.api.js'
import Cookies from 'js-cookie'
import { setTimeout } from 'timers';
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: 'CustomerSalaryImportModal',

  watch: {
  },

  computed: {
    setFormItem () {
      if (!this.axsEnableSwitch) { // 没有启用安心税
        return this.formItem
      } else {
        return [...this.formItem.slice(0, 3), ...this.formItem.slice(4, this.formItem.length + 1)]
      }
    }
  },

  data () {
    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      baseUrl: baseUrl,
      isShowCustomerSalaryImportModal: false,
      isShowFurtherModal: false,
      isNowMonth: false,
      baseUrl: baseUrl,
      formImport: {
        customerId: '',
        customerName: '',
        salaryMonth: new Date(), // 计薪月份
        payDay: '',
        salaryStartTime: '',
        taxMonth: new Date(),
        deductionType: '',
        salaryEndTime: '',
        incomeType: '',
        // axsPlanName: '',
        fileName: ''
      },
      formItem: [
        { type: 'datePicker', label: '工资月份：', placeholder: '请选择工资月份', prop: 'salaryMonth', model: 'salaryMonth', style: '', isShow: true },
        { type: 'select', label: '客户名称：', placeholder: '请输入客户名称', prop: 'customerName', model: 'customerName', style: 'is-required', isShow: true, options: 'customers', fn: 'customerChange' },
        { type: 'select', label: '工资发放日期：', placeholder: '请输入工资发放日期', prop: 'payDay', model: 'payDay', style: '', isShow: true, options: 'days' },
        { type: 'interval', label: '计薪起止日期', placeholder1: '开始日期', prop1: 'salaryStartTime', model1: 'salaryStartTime', placeholder2: '结束日期', prop2: 'salaryEndTime', model2: 'salaryEndTime', style: '', isShow: true },
        { type: 'datePicker', label: '税款所属月份', placeholder: '请选择税款所属月份', prop: 'taxMonth', model: 'taxMonth', style: '', isShow: true },
        { type: 'radio', label: '社保公积金扣除月份：', placeholder: '请选择社保公积金扣除月份', prop: 'deductionType', model: 'deductionType', style: '', isShow: true, fn: 'deductionTypeChange', radioArr: [{ value: '1', label: '上月' }, { value: '0', label: '当月' }, { value: '2', label: '自定义' }] },
        { type: 'select', label: '收入类型：', placeholder: '请输入收入类型', prop: 'incomeType', model: 'incomeType', style: '', isShow: true, options: 'incomeType' },
        { type: 'fileName', label: '应发工资导入：', placeholder: '请输入应发工资导入', prop: 'fileName', model: 'fileName', style: 'is-required', isShow: true }
      ],
      rules: {
        customerName:[{ required: true, message: '请输入客户名称' }]
      },
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null,
        tableData: [],
        tableTitle: [],
        tableLoading: false
      },
      arrListDown: {
        customers: [],
        days: [],
        incomeType: []
      },
      dateOptionsStart: {
        disabledDate (date) {
          const startTime = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months').startOf('month').format('YYYY-MM-DD') // 上月初
          const endTime = moment().endOf('month').format("YYYY-MM-DD") // 当月末
          return date && (date.valueOf() < startTime) || (date.valueOf() > endTime)
        }
      },
      dateOptionsEnd: {
        disabledDate (date) {
          const startTime = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months').startOf('month').format('YYYY-MM-DD')
          const endTime = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months').endOf('month').format('YYYY-MM-DD') // 上月末
          return date && (date.valueOf() < startTime) || (date.valueOf() > endTime)
        }
      },
      datePickerDefault: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months').startOf('month').format('YYYY-MM-DD'), // 上月初
      salaryStartTimeDefault: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months').startOf('month').format('YYYY-MM-DD'), // 上月初
      salaryEndTimeDefault: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months').endOf('month').format('YYYY-MM-DD'), // 上月末
      // templateDownLoadUrl: '/api/CustomerSalary/ExportTemplate?random=' + Math.floor(Math.random()*10),
      templateDownLoadUrl: null,
      customerTemplateDownLoadUrl: null,
      // isError: false
      errorData: {
        errorId: '',
        isError: false,
        downLoadUrl: '/api/CustomerSalary/ExportErrorFile?fileName='
      },
      isCanUpload: true,
      isCanSubmit: true,
      axsEnableSwitch: false,
      isCustomerTemplate: false,
    }
  },

  mounted () {
    this.getImportConfig()
    console.log('salaryStartTimeDefault'+this.salaryStartTimeDefault)
    console.log('salaryEndTimeDefault'+this.salaryEndTimeDefault)
    // console.log('❤ 当前月初：', moment().startOf('month').format("YYYY-MM-DD"))
    // console.log('❤ 上个月初：', moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months').startOf('month').format('YYYY-MM-DD'))
    // console.log('❤ 当前月末：', moment().endOf('month').format("YYYY-MM-DD"))
    // console.log('❤ 上个月末：', moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months').endOf('month').format('YYYY-MM-DD'))
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, param) {
      this[methodsWords](param)
    },

    // ok () {
    //   // this.$Message.info('Clicked ok')
    //   // console.log('表单内容：', this.formImport)
    //   // console.log('表单内容：', this.formImport)
    //   this.import()
    // },
    // ok () {
    //   console.log('确定')
    //   this.$emit('uploadFileOk', this.importExcel)
    // },

    cancel () {
      // this.$Message.info('Clicked cancel')
      this.isShowCustomerSalaryImportModal = false
    },

    show () {
      setTimeout(()=>{
        this.handleChangeDatePicker('salaryStartTime',this.salaryStartTimeDefault)
      })
      this.$refs.formImport.resetFields()
      this.isCanSubmit = true
      this.isShowCustomerSalaryImportModal = true
      this.isCustomerTemplate = false
    },

    handleUploadFile () {
      Common.initUpload(this.importExcel)
    },

    handleBeforeUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      console.log('file: ', file)
      console.log('fileExt: ', fileExt)
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        Common.readFile(file, this.importExcel)
        this.importExcel.file = file
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
    },

    handleUploadSuccess (res, file, fileList) {
      console.log('＋ 应发工资导入文件res: ', res)
      console.log('＋ 应发工资导入文件file: ', file)
      console.log('＋ 应发工资导入文件fileList: ', fileList)
      if (res.success) {
        this.formImport.fileName = res.data
        // this.importExcel.file = fileList
        this.isCanUpload = false
      }
      console.log('💗', this.formImport)
    },

    handleUploadRemove (res, file, fileList) {
      this.isCanUpload = true
      console.log('✂ 应发工资导入文件res: ', res)
      console.log('✂ 应发工资导入文件file: ', file)
      console.log('✂ 应发工资导入文件fileList: ', fileList)
    },

    // 获取薪资导入页面数据源
    async getImportConfig () {
      var params = {
        CustomerGUID: '',
        CustomerName: '',
        SalaryMonth: ''
      }
      let res = await CustomerSalaryApi.getImportConfig(params)
      console.log('获取薪资导入页面数据源res: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        this.arrListDown.customers = result.customers
        this.arrListDown.incomeType = result.incomeType
        this.axsEnableSwitch = result.axsEnableSwitch
        this.templateDownLoadUrl = this.baseUrl + result.templateUrl + '?random=' + Math.floor(Math.random() * 10)
        this.customerTemplateDownLoadUrl = this.baseUrl + result.customerTemplateUrl + '?random=' + Math.floor(Math.random() * 10)
        console.log('❌ this.axsEnableSwitch: ', this.axsEnableSwitch)
        console.log('❌ this.baseUrl: ', this.baseUrl)
        console.log('❌ this.templateDownLoadUrl: ', this.templateDownLoadUrl)
        console.log('❌ this.customerTemplateDownLoadUrl: ', this.customerTemplateDownLoadUrl)

        // if (!this.axsEnableSwitch) {
        //   this.formItem.map(item => {
        //     if (item.model === 'axsPlanName') {
        //       item.isShow = false
        //     }
        //   })
        // }
      } else {
        // this.tableData = []
      }
      // this.loading = false
    },

    // 改变所选择客户
    customerChange (selectedCustomerId) {
      console.log('所选择的客户ID是：', selectedCustomerId)
      this.formImport.customerId = selectedCustomerId
      this.getDayList()
    },

    // 根据客户ID获取工资发放日期列表
    async getDayList () {
      var params = {
        CustomerGUID: this.formImport.customerId,
        CustomerName: this.formImport.customerName,
        SalaryMonth: this.formImport.salaryMonth
      }
      let res = await CustomerSalaryApi.getDayList(params)
      console.log('根据客户ID获取工资发放日期列表res: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        this.arrListDown.days = result
      } else {
        this.arrListDown.days = []
      }
    },

    taxMonth (model, val) {
      this.formImport[model] = moment(val).format("YYYY-MM")
    },

    handleChangeDatePicker (model, val) {
      console.log(model,val)
      var nowMonth = new Date().getMonth()
      // console.log('当前月份是: ' + nowMonth)
      // console.log('model: ' + model + ', val: ' + val)
      var selectMonth = val ? (new Date(val)).getMonth() : (new Date()).getMonth()
      // console.log('选中的日期是: ', val, '选中的月份是: ', selectMonth)
      if (+nowMonth === +selectMonth) {
        this.isNowMonth = true
      } else {
        this.isNowMonth = false
      }
      // console.log('截止日期是: ', this.formImport.salaryEndTime)
      // this.formImport.salaryMonth = val
      // this.getDayList()
      this.formImport[model] = val
      // console.log('☆ val ☆ ', val)
      // console.log('☆ 选中月份的月初 ☆ ', moment(val).startOf('month').format("YYYY-MM-DD"))
      // console.log('☆ 选中月份的月末 ☆ ', moment(val).endOf('month').format("YYYY-MM-DD"))
      if (model === 'salaryStartTime') {
        this.salaryEndTimeDefault = moment(val).endOf('month').format("YYYY-MM-DD")
        // console.log('this.salaryEndTimeDefault: ' + this.salaryEndTimeDefault)
        this.dateOptionsEnd = {
          disabledDate (date) {
            const startTime = moment(val).startOf('month').format("YYYY-MM-DD")
            const endTime = moment(val).endOf('month').format("YYYY-MM-DD")
            return date && (date.valueOf() < startTime) || (date.valueOf() > endTime)
          }
        }
      }
    },

    // fileChange (e) {
    //   var files = e.target.files[0]
    //   this.formImport.fileName = files
    //   console.log('this.formImport.fileName: ', this.formImport.fileName)
    //   console.log('this.formImport: ', this.formImport)
    // },

    // 薪资导入
    async handleImport () {
      this.isCanSubmit = false

      let salaryMonth = new Date(this.formImport.salaryMonth).getMonth()+1
      let SalaryStartTime = this.formImport.salaryStartTime || this.salaryStartTimeDefault
      let SalaryEndTime = this.formImport.salaryEndTime || this.salaryEndTimeDefault
      if(isNaN(salaryMonth)){
        if(this.formImport.payDay){
          this.$Message.error({
            content: '请选择工资月份',
            duration: 10,
            closable: true
          })
        }
        this.isCanSubmit = true
        return
      } 
      // else {
      //   // 计薪起止时间与工资月份相关联进行控制，假如工资月份是2月，则计薪起止时间只能选1月/2月/3月的时间段
      //   if (new Date(SalaryStartTime).getTime()<new Date(SalaryEndTime).getTime()){
      //     let sMonth = new Date(SalaryStartTime).getMonth()+1
      //     let eMonth = new Date(SalaryEndTime).getMonth()+1
      //     var nowdays = new Date(this.formImport.salaryMonth);
      //     var year = nowdays.getFullYear();
      //     var month = nowdays.getMonth();
      //     var cyear = year;
      //     var cmonth = month;
      //     if(month==0){
      //         cmonth=12;
      //         cyear=year-1;
      //     }
      //     if (month < 10) {
      //         cmonth = "0" + month;
      //     }
      //     var firstDay = moment(cyear + "-" + cmonth,"YYYY-MM").startOf('month');//上个月的第一天
      //     cyear = year
      //     cmonth = ++month
      //     if (month<9) {
      //       cmonth = '0'+(month+1)
      //     } else {
      //       cmonth = month+1
      //     }
      //     if (month == 12){
      //       cyear=++year;
      //       cmonth = 1
      //     }
      //     var lastDate =  moment(cyear + "-" + cmonth,"YYYY-MM").endOf("month");
      //     if(new Date(SalaryStartTime).getTime()<new Date(firstDay).getTime()||new Date(SalaryEndTime).getTime()>new Date(lastDate).getTime()){
      //       this.$Message.error({
      //         content: '计薪起止时间应在'+new Date(firstDay).getFullYear()+'年'+(new Date(firstDay).getMonth()+1)+'月-'+new Date(lastDate).getFullYear()+'年'+(new Date(lastDate).getMonth()+1)+'月之间',
      //         duration: 10,
      //         closable: true
      //       })
      //       this.isCanSubmit = true
      //       return
      //     }
      //   }else{
      //     this.$Message.error({
      //       content: '计薪起止时间不能晚于结束时间',
      //       duration: 10,
      //       closable: true
      //     })
      //     this.isCanSubmit = true
      //     return
      //   }
      //   console.log(new Date(SalaryStartTime).getTime(),new Date(SalaryEndTime).getTime())
      // }

      var params = {
        CustomerGUID: this.formImport.customerId,
        CustomerName: this.formImport.customerName,
        DeductionType: this.formImport.deductionType,
        // SalaryStartTime: this.salaryStartTimeDefault,
        // SalaryEndTime: this.salaryEndTimeDefault,
        SalaryStartTime: this.formImport.salaryStartTime || this.salaryStartTimeDefault,
        SalaryEndTime: this.formImport.salaryEndTime || this.salaryEndTimeDefault,
        PayDay: this.formImport.payDay,
        IncomeType: this.formImport.incomeType,
        fileName: this.formImport.fileName,
        TaxMonth: this.formImport.taxMonth,
        SalaryMonth: this.formImport.salaryMonth
        
        // AxsPlanName: this.formImport.axsPlanName
      }
      console.log('薪资导入params: ', params)
      let res = await CustomerSalaryApi.import(params)
      console.log('薪资导入res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.errorData.isError = false
        this.isShowCustomerSalaryImportModal = false
        this.$emit('query')
      } else {
        this.isCanSubmit = true
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
        this.isShowCustomerSalaryImportModal = true
        if (res.data.data) {
          this.errorData.isError = true
          this.errorData.errorId = res.data.data
          this.errorData.downLoadUrl = baseUrl + 'api/CustomerSalary/ExportErrorFile?fileName=' + res.data.data
        }
      }
    },

    handleClearFiles () {
      var file = this.$refs.upload
      if (file && file.length) {
        file.forEach(item => {
          item.clearFiles()
        })
      }
    },

    handleShowFurtherModal () {
      this.isShowFurtherModal = true
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    },

    deductionTypeChange (value) {
      console.log('扣除月份 value: ', value)
      if (value == 2) {
        this.isCustomerTemplate = true
      } else {
        this.isCustomerTemplate = false
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
